﻿using B.Auth.APi.Application.Command.RoleMenus;
using B.Auth.Domain.Entity;
using B.Auth.Domain.Repository;
using B.Auth.Enum;
using MediatR;

namespace B.Auth.APi.Application.CommandHand.RoleMenu
{
    public class RoleMenuCommandHand : IRequestHandler<RoleMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleMenuModel> _rolemenu;
      

        public RoleMenuCommandHand(IBaseRepository<RoleMenuModel> rolemenu)
        {
            _rolemenu = rolemenu;
        }

       

        public Task<ApiResult<int>> Handle(RoleMenuCommand request, CancellationToken cancellationToken)
        {
            
           var resut=new ApiResult<int>();

           List<int> menuid=request.menuid.Split(',').Select(x=>Convert.ToInt32(x)).ToList();


            foreach (var item in menuid)
            {

                var role = _rolemenu.GetAll().FirstOrDefault(x => x.RID == request.roleid);
                if (role != null)
                { 
                   _rolemenu.Delect(role);
                
                }

            }

            foreach (var item in menuid)
            {

                RoleMenuModel roleMenu = new RoleMenuModel()
                {

                    RID = request.roleid,
                    MID = item


                };
                _rolemenu.Addlist(roleMenu);

            }
            resut.Message = "添加成功";
            resut.Code = ApiEnum.ok;
            return Task.FromResult(resut);



        }
    }
}
